package com.hu.util.email;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author author
 * @date 2024-10-12 11:29
 */
public class EmailUtil {

    private static final String EMAIL_SAVE_FILE = "d:/mail.eml";
    private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);

    /**
     * 创建邮件并保存到本地
     * @param emailDTO
     */
    public static void createMessage(EmailDTO emailDTO) {
        try {
            Message message = new MimeMessage(Session.getInstance(System.getProperties()));
            message.setFrom(new InternetAddress(convertRecipients(emailDTO.getFrom())));
            // 收件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(convertRecipients(emailDTO.getTo())));
            // 抄送人
            if (emailDTO.getCc() != null && emailDTO.getCc().length() > 0) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(convertRecipients(emailDTO.getCc())));
            }
            // 密送人
            if (emailDTO.getBcc() != null && emailDTO.getBcc().length() > 0) {
                message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(convertRecipients(emailDTO.getBcc())));
            }
            message.setSubject(emailDTO.getSubject());
            // create the message part
            MimeBodyPart content = new MimeBodyPart();
            // fill message
            content.setText(emailDTO.getContent());
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(content);
            // add attachments
            if (emailDTO.getAttachments() != null && emailDTO.getAttachments().size() > 0) {
                for(File file : emailDTO.getAttachments()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataSource source = new FileDataSource(file);
                    attachment.setDataHandler(new DataHandler(source));
                    attachment.setFileName(file.getName());
                    multipart.addBodyPart(attachment);
                }
            }
            // integration
            message.setContent(multipart);
            // store file
            message.writeTo(new FileOutputStream(EMAIL_SAVE_FILE));
        } catch (MessagingException ex) {
            logger.error("创建邮件异常", ex);
        } catch (IOException ex) {
            logger.error("邮件文件流异常", ex);
        }
    }

    /**
     * 处理收件人、发件人等中文乱码问题
     * @param recipients
     * @return
     */
    /**
     * 处理收件人、发件人等中文乱码问题
     * @param recipients
     * @return
     */
    public static String convertRecipients(String recipients) {
        if (recipients == null || recipients.isEmpty()) {
            return null;
        }
        String[] recipientsArray = recipients.split(",");
        StringBuilder encodedRecipients = new StringBuilder();
        for (int i = 0; i < recipientsArray.length; i++) {
            if (encodedRecipients.length() > 0) {
                encodedRecipients.append(", ");
            }
            String receiver = recipientsArray[i];
            try {
                if (receiver.contains("(")) {
                    int leftPos = receiver.indexOf("(");
                    encodedRecipients.append(javax.mail.internet.MimeUtility.encodeText(receiver.substring(0, leftPos), MimeUtility.mimeCharset("UTF-8"), null))
                            .append(" <").append(receiver, leftPos + 1, receiver.length() - 1).append(">");
                } else {
                    encodedRecipients.append(receiver);
                }
            } catch (Exception e) {
                encodedRecipients.append(receiver);
            }
        }
        return encodedRecipients.toString();
    }

    /**
     * 获取邮件的标题，解决乱码问题
     * @param message
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getSubject(MimeMessage message) throws MessagingException, UnsupportedEncodingException {
        String subject = new String(message.getHeader("subject")[0].getBytes(StandardCharsets.ISO_8859_1), "gb2312");
        return subject.startsWith("?=") ? MimeUtility.decodeText(subject) : subject;
    }

    public static void main(String[] args) {
        List<File> attachments = new ArrayList<>();
        attachments.add(new File("d:/邮件测试.txt"));
        EmailDTO emailDTO = new EmailDTO();
        emailDTO.setFrom("zhangsan@example.com");
        emailDTO.setTo("李四(lisi@example.com)");
        emailDTO.setCc("张三(zhangsan@example.com),王五(wangwu@example.com)");
        emailDTO.setBcc("to2@example.com");
        emailDTO.setSubject("Email Subject");
        emailDTO.setContent("This is the email body");
        emailDTO.setAttachments(attachments);
        createMessage(emailDTO);
    }
}
